<!--商品规范申报-->
<template>
    <Modal
        v-model="detailsModal"
        width="746"
        :closable="false"
        class-name="details-modal"
    >
        <div slot="header" >
            商品规范申报
            <Icon class="f-fr" type="ios-close" @click="cancelModal"/>
        </div>
        <Form class="clearfix" :label-width="158" ref="detailsFormRef">
            <FormItem v-for="(item, index) in detaiList" :key="item.elementNo" class="detail-model-form">
                <span slot="label">
                    <span style="color:#F45050;" v-if="item.isRequired == true">*</span> {{item.elementName}}</span>
                <RemoteSearch
                    v-if="item.elementName === '品牌类型'"
                    :disabled="editORshow "
                    v-model="detaiList[index].elementValue"
                    :list="brandList"
                    keyword=""
                    keywordFiled="dataName"
                    valueField="dataCode"
                    :labelFieldList="['dataName']"
                    @get-all="changeItem"
                    @on-enter="setFocus($event, index)"
                >
                </RemoteSearch>
                <RemoteSearch
                    v-if="item.elementName === '出口享惠情况'"
                    :disabled="editORshow || valueDisabled"
                    v-model="detaiList[index].elementValue"
                    :list="perferenceList"
                    keyword=""
                    keywordFiled="dataName"
                    valueField="dataCode"
                    :labelFieldList="['dataName']"
                    @get-all="changeItem"
                    @on-enter="setFocus($event, index)"
                >
                </RemoteSearch>
                <Input
                    v-if="item.elementName != '品牌类型' && item.elementName != '出口享惠情况'"
                    type="text"
                    :disabled="editORshow"
                    v-model="item.elementValue"
                    @on-change="changeItem"
                    @on-enter="setFocus($event, index)"
                >
                </Input>
            </FormItem>
        </Form>
        <div>规格型号： {{ detailTxtList }}</div>
        <div slot="footer">
            <Button type="default" @click="cancelModal">取消</Button>
            <Button type="primary" @click="saveDetail">确定</Button>
        </div>
    </Modal>
</template>

<script>
import { trim } from '@/libs/tools'
import { getGoodsCode } from '@/api/declare'
import $ from 'jquery'
import RemoteSearch from '@/view/components/RemoteSearch'

export default {
    name: 'DetailsModal',
    components: {
        RemoteSearch
    },
    data () {
        return {
            detailsModal: false,
            detaiList: [],
            detailTxtList: '',
            editORshow: null,
            brandList: [
                {
                    'dataCode': '0',
                    'dataName': '0-无品牌'
                },
                {
                    'dataCode': '1',
                    'dataName': '1-境内自主品牌'
                },
                {
                    'dataCode': '2',
                    'dataName': '2-境内收购品牌'
                },
                {
                    'dataCode': '3',
                    'dataName': '3-境外品牌(贴牌生产)'
                },
                {
                    'dataCode': '4',
                    'dataName': '4-境外品牌(其它)'
                }
            ],
            perferenceList: [
                {
                    'dataCode': '0',
                    'dataName': '0-出口货物在最终目的国(地区)不享受优惠关税'
                },
                {
                    'dataCode': '1',
                    'dataName': '1-出口货物在最终目的国(地区)享受优惠关税'
                },
                {
                    'dataCode': '2',
                    'dataName': '2-不能确定在最终目的国(地区)享受优惠关税'
                },
                {
                    'dataCode': '3',
                    'dataName': '3-不适用于进口报关单'
                }
            ],
            type: '',
            valueDisabled: '',
            firstOption: {}
        }
    },
    methods: {
        init (codeTs, goodsModel, type, editORshow, valueDisabled) {
            this.propGoodsModel = goodsModel
            this.type = type
            this.valueDisabled = typeof valueDisabled === 'boolean'
                ? valueDisabled
                : type === 'I'
            this.detailTxtList = ''
            this.editORshow = editORshow
            this.detailsModal = true
            this.detaiList = []
            this.$nextTick(() => {
                let params = {
                    codeTs: codeTs
                }
                getGoodsCode(params).then(res => {
                    if (res.data.code === '0000') {
                        if (res.data.data) {
                            let list = res.data.data.details || []
                            const len = list.length - 1
                            let valList = goodsModel ? goodsModel.split('|') : []
                            list.forEach((item, index) => {
                                const def = valList[index] || ''
                                item.elementValue = def
                                if (def === '' && item.elementName === '出口享惠情况' && type === 'I') {
                                    item.elementValue = '3'
                                }
                                if (index === len) {
                                    item.elementValue = valList.slice(index).join('|')
                                }
                            })
                            this.detaiList = res.data.data.details
                            this.detailTxtList = goodsModel
                        }
                    } else {
                        this.$Message.error(res.data.msg)
                    }
                    if (this.detaiList.length > 0) {
                        this.$nextTick(() => {
                            this.$refs.detailsFormRef.$el.querySelector('.ivu-input').focus()
                        })
                    }
                })
            })
        },

        cancelModal () {
            this.detailsModal = false
        },

        changeItem () {
            let v = this.detaiList
                .map(item => {
                    return item.elementValue && trim(item.elementValue) || ''
                })
                .join('|')
                .replace(/\|+$/, '')
            this.detailTxtList = v || this.propGoodsModel
        },

        saveDetail () {
            let len = this.detaiList.length
            for (let i = 0; i < len; i++) {
                if (this.detaiList[i].isRequired && this.detaiList[i].elementValue === '') {
                    this.$Message.error(this.detaiList[i].elementName + '不能为空')
                    return false
                }
            }

            this.detailTxtList = this.detailTxtList.replace(/[\r\n]/g, '') // 去掉回车换行

            if (this.detailTxtList.length > 255) {
                this.$Message.warning('规格型号长度不能超过255位')
                return false
            }
            this.$emit('saveDetail', this.detailTxtList)
            this.cancelModal()
        },

        setFocus (e, index) {
            if (e.keyCode === 13) {
                this.setOhterValue(e, index)
                this.$nextTick(() => {
                    let target = $(e.target).parents('.ivu-form-item').next()

                    if (target.find('.ivu-input:disabled').length > 0) {
                        target = target.next()
                    }
                    if (target.length === 0) { // 最后一个输入框
                        this.changeItem()
                        this.saveDetail()
                    }

                    if (target.find('.ivu-select-input').length) {
                        target.find('.ivu-select-input').focus()
                    } else if (target.find('.ivu-input').length) {
                        target.find('.ivu-input').focus()
                    }
                })
            }
        },

        queryBrandList (val, index) {
            if (!String(val).replace(/^\s+|\s+$/g, '')) {
                this.detaiList[index].elementValue = ''
                this.changeItem()
            }
        },
        fuzzQuery (v, list, cb) {
            if (v) {
                const arr = list.find(item =>
                    JSON.stringify([item.dataCode, item.dataName])
                        .toUpperCase()
                        .includes(v)
                )
                arr && cb(arr)
            }
        },
        brandEnter (event, index, list, item) {
            this.changeItem()
        },

        queryPerferenceList (val, index) {
            if (!String(val).replace(/^\s+|\s+$/g, '')) {
                this.detaiList[index].elementValue = ''
                this.changeItem()
            }
        },

        perferenceEnter (event, index, list, item) {
            const v = trim(String(event.target.value)).toUpperCase().split('-')[0]
            if (v) {
                this.fuzzQuery(v, list, (data) => {
                    this.detaiList[index].elementValue = ''
                    this.perferenceList = list.slice()
                    this.$nextTick(() => {
                        this.detaiList[index].elementValue = data.dataCode
                        this.changeItem()
                    })
                })
            }
        },
        // 设置其他选项数据  如果输入的内容包含 '|'  分割 '|' 赋值给后面的数据(TAPD:1006761)
        // 修改快速录入需求:当前输入行开始赋值(TAPD:1007037)
        setOhterValue (event, index) {
            const value = trim(event.target.value)
            const len = this.detaiList.length - 1
            // 如果最后一个值回车时 判断是否有改变 没有改变则不做任何处理
            if (len === index) return
            let values = value.split('|')
            if (values.length > 1) {
                const last = values.splice(len - index).join('|')
                last && values.push(last)
                values.forEach((v, j) => {
                    const i = index + j
                    if (this.detaiList[i]) {
                        const {
                            elementName
                        } = this.detaiList[i]
                        const ev = trim(v)
                        if (elementName === '出口享惠情况' && this.valueDisabled) return
                        let target = 0
                        if (ev && elementName === '品牌类型') {
                            target = this.brandList.findIndex(obj => obj.dataCode == ev)
                        } else if (ev && elementName === '出口享惠情况') {
                            target = this.perferenceList.findIndex(obj => obj.dataCode == ev)
                        }
                        this.detaiList[i].elementValue = target < 0 ? '' : ev
                    }
                })
                this.changeItem()
            }
        }
    } // methods end
}
</script>

<style lang="less">
    .details-modal {
        .ivu-modal-body {
            padding: 10px 20px;
        }
        .ivu-form-item {
            margin-bottom: 0 !important;
        }
        .ivu-select-selection, .ivu-select-input, .ivu-input-wrapper, .ivu-input {
            height: 18px !important;
            line-height: 18px !important;
            font-size: 12px;
        }
    }

    @media screen and (max-width: 1400px) {
        .details-modal {
            .ivu-modal-body {
                height: 300px !important;
            }
        }
    }
</style>
